#include <utility>

class Solution {
public:
    int mySqrt(int x) {
        if (x == 0) {
            return 0;
        }
        if (x <= 3) {
            return 1;
        }
        int left = 2;
        int right = std::min(x, (1 << 16));
        int mid;
        while (left < right - 1) {
            mid = (left + right) / 2;
            long long tmp = (long long)mid * mid;
            if (tmp < x) {
                left = mid;
            }
            else if (tmp > x) {
                right = mid;
            }
            else {
                return mid;
            }
        }
        return left;
    }
};